<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="班级名称" prop="className">
        <el-input
          v-model="queryParams.className"
          placeholder="请输入班级名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任课教师" prop="teacherName">
        <el-input
          v-model="queryParams.teacherName"
          placeholder="请输入教师姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in tgs_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:grade:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:grade:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:grade:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:grade:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="gradeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="班级ID" align="center" prop="classId" />
      <el-table-column label="班级名称" align="center" prop="className" />
      <el-table-column label="任课教师" align="center" prop="teacherName">
        <template #default="scope">
          <span :class="{ 'disabled-teacher': isTeacherDisabled(scope.row.teacherId) }">{{ scope.row.teacherName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">
            <dict-tag :options="tgs_status" :value="scope.row.status"/>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:grade:edit']">修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:grade:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改班级管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="gradeRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="班级名称" prop="className">
          <el-input v-model="form.className" placeholder="请输入班级名称" />
        </el-form-item>
        <el-form-item label="任课教师" prop="teacherId">
          <el-select v-model="form.teacherId" placeholder="请选择任课教师" @change="handleTeacherChange">
            <el-option
              v-for="teacher in teacherList"
              :key="teacher.teacherId"
              :label="teacher.teacherName"
              :value="teacher.teacherId"
              :class="{ 'disabled-teacher-option': teacher.disabled }"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in tgs_status"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Grade">
import { listGrade, getGrade, delGrade, addGrade, updateGrade } from "@/api/manage/grade";
import { listTeacher } from "@/api/manage/teacher";
import useUserStore from '@/store/modules/user';

const { proxy } = getCurrentInstance();
const { tgs_status } = proxy.useDict('tgs_status');
const userStore = useUserStore();

const gradeList = ref([]);
const teacherList = ref([]); // 教师列表
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    className: null,
    teacherName: null,
    status: null,
  },
  rules: {
    className: [
      { required: true, message: "班级名称不能为空", trigger: "blur" }
    ],
    teacherId: [
      { required: true, message: "教师不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 获取教师列表 */
function getTeacherList() {
  // 只获取启用状态的教师列表
  return listTeacher({ status: 0 }).then(response => {
    teacherList.value = response.rows || [];
  });
}

/** 查询班级管理列表 */
function getList() {
  // 先获取启用状态的教师列表
  getTeacherList().then(() => {
    loading.value = true;
    listGrade(queryParams.value).then(response => {
      gradeList.value = response.rows;
      total.value = response.total;
      
      // 处理禁用状态的教师
      const disabledTeacherIds = new Set();
      gradeList.value.forEach(grade => {
        const teacherExists = teacherList.value.some(t => t.teacherId === grade.teacherId && !t.disabled);
        if (!teacherExists && grade.teacherId && grade.teacherName) {
          disabledTeacherIds.add(grade.teacherId);
        }
      });
      
      // 如果有禁用教师，将其添加到教师列表中（带禁用标记）
      if (disabledTeacherIds.size > 0) {
        const tempTeacherList = [...teacherList.value];
        
        gradeList.value.forEach(grade => {
          if (disabledTeacherIds.has(grade.teacherId)) {
            // 检查是否已经添加过该教师
            const existingIndex = tempTeacherList.findIndex(t => t.teacherId === grade.teacherId);
            if (existingIndex === -1) {
              // 添加禁用教师到列表
              tempTeacherList.push({
                teacherId: grade.teacherId,
                teacherName: grade.teacherName,
                disabled: true // 标记为禁用状态
              });
            }
          }
        });
        
        // 更新教师列表
        teacherList.value = tempTeacherList;
      }
      
      loading.value = false;
    });
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    classId: null,
    className: null,
    teacherId: null,
    teacherName: null,
    status: 0,
    remark: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null
  };
  proxy.resetForm("gradeRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.classId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getTeacherList().then(() => {
    // 获取当前用户信息
    const userName = userStore.name;
    const nickName = userStore.nickName;
    
    // 尝试在教师列表中查找匹配的教师
    let matchFound = false;
    
    // 先尝试匹配用户名（工号）
    if (userName) {
      const matchedTeacher = teacherList.value.find(t => t.teacherNumber === userName);
      if (matchedTeacher) {
        form.value.teacherId = matchedTeacher.teacherId;
        form.value.teacherName = matchedTeacher.teacherName;
        matchFound = true;
      }
    }
    
    // 如果没有匹配到工号，尝试匹配昵称（姓名）
    if (!matchFound && nickName) {
      const matchedTeacher = teacherList.value.find(t => t.teacherName === nickName);
      if (matchedTeacher) {
        form.value.teacherId = matchedTeacher.teacherId;
        form.value.teacherName = matchedTeacher.teacherName;
        matchFound = true;
      }
    }
    
    // 如果仍然没有匹配到，选择第一个教师
    if (!matchFound && teacherList.value.length > 0) {
      form.value.teacherId = teacherList.value[0].teacherId;
      form.value.teacherName = teacherList.value[0].teacherName;
    }
    
    open.value = true;
    title.value = "添加班级管理";
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  
  // 先获取启用的教师列表
  getTeacherList().then(() => {
    const _classId = row.classId || ids.value
    getGrade(_classId).then(response => {
      form.value = response.data;
      
      // 检查该班级的任课教师是否在启用的教师列表中
      const teacherExists = teacherList.value.some(t => t.teacherId === form.value.teacherId);
      
      // 如果该教师不在启用列表中（说明已被禁用），需要将其添加到下拉选项中
      if (!teacherExists && form.value.teacherId && form.value.teacherName) {
        // 克隆教师列表，避免修改原始数据
        const tempTeacherList = [...teacherList.value];
        
        // 添加当前已禁用的教师到列表中
        tempTeacherList.push({
          teacherId: form.value.teacherId,
          teacherName: form.value.teacherName,
          disabled: true // 标记为禁用状态
        });
        
        // 更新教师列表
        teacherList.value = tempTeacherList;
      }
      
      open.value = true;
      title.value = "修改班级管理";
    });
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["gradeRef"].validate(valid => {
    if (valid) {
      if (form.value.classId != null) {
        updateGrade(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addGrade(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _classIds = row.classId || ids.value;
  proxy.$modal.confirm('是否确认删除班级管理编号为"' + _classIds + '"的数据项？').then(function() {
    return delGrade(_classIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/grade/export', {
    ...queryParams.value
  }, `grade_${new Date().getTime()}.xlsx`)
}

// 处理教师选择变化
function handleTeacherChange(value) {
  // 在教师列表（包括可能添加的禁用教师）中查找选中的教师
  const selectedTeacher = teacherList.value.find(t => t.teacherId === value);
  if (selectedTeacher) {
    form.value.teacherId = selectedTeacher.teacherId;
    form.value.teacherName = selectedTeacher.teacherName;
  }
}

// 判断教师是否为停用状态
function isTeacherDisabled(teacherId) {
  // 在教师列表中查找该教师
  const teacher = teacherList.value.find(t => t.teacherId === teacherId);
  
  // 如果教师不在列表中，或者教师被标记为禁用状态，则返回true
  return !teacher || teacher.disabled === true;
}

onMounted(() => {
  getList();
});
</script>

<style scoped>
.disabled-teacher {
  color: #F56C6C;
  font-weight: bold;
}

.disabled-teacher-option {
  color: #F56C6C !important;
  font-weight: bold;
}
</style>
